<?php

/**
 * Lord_View_Smarty_SmartyAdvanced
 * 
 * @package Basic
 * @author Игорь Будасов aka Lord <igor.budasov@gmail.com>
 */
 

require_once 'Smarty/Smarty.class.php';
require_once 'Smarty/Smarty_Compiler.class.php';

class Lord_View_Smarty_SmartyAdvanced extends Smarty
{
	private $_placeHolders = array();
	public $_zendView;

/*------------------------------------------------------------------------------*/

	public function __construct()
	{              
		parent::__construct();
		$this->compiler_class = 'SmartyAdvancedCompiler';
	}

/*------------------------------------------------------------------------------*/
	
	public function setZendView(Zend_View_Interface $view)
	{    
		// подключаем доджо     
		$view->addHelperPath('Zend/Dojo/View/Helper/', 'Zend_Dojo_View_Helper');
		// Устанавливаем путь/префикс для помощников вида
		$view->addHelperPath('Lord/View/Helper/', 'Lord_View_Helper');
        
        // зачитываем конфиг                
        $preConfig = new Zend_Registry();
        $config = $preConfig->get('config');
        
        // Задание основных URL
        $view->baseUrl    = $config->url->base;
        $view->imagesUrl  = $config->url->images;
        $view->cssUrl     = $config->url->css;
        $view->jsUrl      = $config->url->js;
        $view->fontsUrl   = $config->url->fonts;
        $view->contentUrl = $config->url->content;
        $view->siteName   = $config->common->siteName;
             
		$this->_zendView = $view;
	}

/*------------------------------------------------------------------------------*/
	
	public function callViewHelper($name,$args)
	{      
		$helper = $this->_zendView->getHelper($name);
                     
		return call_user_func_array(array($helper,$name),$args);
	}
	
/*------------------------------------------------------------------------------*/

	public function getPlaceHolder($name)
	{
		if(isset($this->_placeHolders[$name]))
			return $this->_placeHolders[$name];
		else
			return '';
	}

/*------------------------------------------------------------------------------*/
	
	public function createPlaceHolder($name,$content)
	{
		$this->_placeHolders[$name] = $content;
	}
	
/*------------------------------------------------------------------------------*/
}
		  
/**
 * SmartyAdvancedCompiler
 * 
 * @package Basic
 * @author Игорь Будасов aka Lord <igor.budasov@gmail.com>
 */

class SmartyAdvancedCompiler extends Smarty_Compiler
{
	private $_zendView;

/*------------------------------------------------------------------------------*/
	
	public function __construct()
	{
		parent::__construct();
		$this->_zendView = new Zend_View();
		// подключаем доджо     
		//$this->_zendView->addHelperPath('Zend/Dojo/View/Helper/', 'Zend_Dojo_View_Helper');
		// Устанавливаем путь/префикс для помощников вида
		$this->_zendView->addHelperPath('Lord/View/Helper/', 'Lord_View_Helper');
	}
	
/*------------------------------------------------------------------------------*/
	
	function _compile_compiler_tag($tagCommand, $tagArgs, &$output)
	{        
		@$found = parent::_compile_compiler_tag($tagCommand,$tagArgs,$output);
		
		if(!$found)
		{
            $view = Zend_Registry::get('smarty'); 
			//Check if helper exists and create output
			$helper = $view->getHelper($tagCommand);	
					
			$helperArgs = array(); 
			//var_export($tagArgs);die();
			if($tagArgs !== null)
			{     
				$params = explode(' ',$tagArgs); 
				foreach($params as $p)
				{
                    //Split each key=value pair to vars
                    list( $key, $value ) = explode( '=', $p, 2);
                    $key = trim($key);
                    $value = trim($value);

                    //If there's a dot in the key, it means we
                    //need to use associative arrays
                    if( strpos( $key, '.' ) != 0 ) 
                    {
                        list( $key, $section ) = explode( '.', $key );
                    }
                    //Use Smarty's own functions to parse the value
                    //so that if there's a variable, it gets changed to
                    //properly point at a template variable etc.
                    $value = $this->_parse_var_props( $value );
                    
                    //Put the value into the arg array
                    if( $section == '' ) 
                    {
                        if( array_key_exists( $key, $helperArgs ) ) 
                        {
                            if( is_array( $helperArgs[$key])) 
                            {
                                $helperArgs[ $key ][] = $value;
                            } 
                            else 
                            {
                                $helperArgs[ $key ] = array( $helperArgs[ $key ], $value );
                            }
                        } 
                        else 
                        {
                            $helperArgs[$key] = $value;
                        }
                    } 
                    else 
                    {
                        if( !is_array( $helperArgs[ $key ] ) ) 
                        {
                            $helperArgs[ $key ] = array();
                        }

                        $helperArgs[ $key ][ $section ] = $value;
                        $section = '';
                    }
                }
			}    
            
            //Save the code to put to the template in the output   
			$output = "<?php echo \$this->callViewHelper('$tagCommand',array(".$this->_createParameterCode($helperArgs).")); ?>";
			$found = true;
		}

		return $found;
	}

/*------------------------------------------------------------------------------*/
	
    /**
    * This function creates the code for the helper params
    *
    * @param array $params
    * @return string $code
    * @access private
    */
    
    private function _createParameterCode($params)
	{    
        $code = '';
           
        $i = 1;
        $pCount = count($params);
                   
        foreach($params as $k=>$p)
        {        
            if(is_array($p) and $k == 'assoc') 
            {    
                $code .= 'array(';
                $j = 0;
                $countP = count($p);
                foreach ($p as $cle=>$elem) 
                {
                    $j = $j+1;
                    $code .= "'".$cle.'\' => '.trim($elem,'"\'').'';
                    if($j != $countP) $code .= ',';
                }
                $code .= ')';
            }
            elseif(is_array($p) and $k != 'param')
                $code .= 'array('.$this->_createParameterCode($p).')';
            elseif(is_array($p))
                $code .= $this->_createParameterCode($p);
            else
                $code .= $p;

            if($i != $pCount)
                $code .= ',';

            $i++;
        }

        return $code;
	}
    
/*------------------------------------------------------------------------------*/
}

?>
